package chessBoard;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PipedInputStream;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import connection.Reader;
import database.MySQLConnection;

/**
 * Trida pro cteni tahu prichazejicich ze serveru za pomoci "style12"
 * 
 * @author dove
 * 
 */
public class Style12 implements Runnable {

	private static final long serialVersionUID = 1L;
	private Thread cteni = null;

	private int memorya = 0;
	private int memoryb = 0;

	private int memory2a = 0;
	private int memory2b = 0;

	private BoardPanel chessBoard;

	private PipedInputStream br;

	private BufferedWriter bw;

	private int time;
	private String from;
	private String to;
	private String name;

	private String word = "";
	private boolean running = false;
	private Time time2;
	private InfoPanel info;

	private static Logger logger = Logger.getLogger("Log");

	/**
	 * Konstruktor pripojuje pipu od Readeru a pripojuje se k databazi
	 */
	public Style12() {
		br = Reader.getReader("Style12");
		bw = Reader.getWriter();
		Convertor.Init();
		chessBoard = new BoardPanel();
		info = new InfoPanel();
		time2 = new Time(info);
	}

	/**
	 * Pripojeni k serveru
	 */
	public void connect() {

		Reader.setReading("Style12");
		running = true;

		cteni = new Thread(this);
		cteni.start();
		time2.start();
	}

	/**
	 * Vraci sachovnici
	 * 
	 * @return
	 */
	public BoardPanel getBoard() {
		return chessBoard;
	}

	/**
	 * Vraci infopanel
	 * 
	 * @return
	 */
	public InfoPanel getInfoPanel() {
		return info;
	}

	/**
	 * Metoda pro zapis prikazu na server
	 * 
	 * @param com
	 *            prikaz
	 */
	public void writeCom(String com) {
		try {
			bw.write(com);
			bw.flush();
		} catch (IOException e) {
			logger.error("", e);
		}
	}

	public void run() {
		int letter = 0;
		while (running) {
			if (!Reader.isConnect()) {
				running = false;
			}
			try {
				if (Reader.isConnect()) {
					letter = br.read();
				} else {
					return;
				}
			} catch (Exception e) {
				logger.error("", e);
			}
			if (letter != 13) {
				word = word.concat(String.valueOf((char) letter));
			}

			if (letter == ' ' || letter == 10) {
				word = "";
			}

			if (word.equals("<12>")) {
				chessBoard.update();
				chessBoard.unsetPressed(memorya, memoryb);
				chessBoard.unsetPressed(memory2a, memory2b);

				word = "";
				while (letter != 13) {
					try {
						letter = br.read();
					} catch (Exception e) {
						logger.error("", e);
					}
					word = word.concat(String.valueOf((char) letter));
				}
				Style12Parser style12 = new Style12Parser(word);

				if (style12.getFlip()) {
					chessBoard.setFlip(true);
					info.setFlip(true);
				} else {
					chessBoard.setFlip(false);
					info.setFlip(false);
				}

				chessBoard.setPositions(style12.getBoardPositions());

				if (style12.getColor().equals("W")) {
					info.setFirstActive(true);
				} else {
					info.setSecondActive(true);
				}

				info.setName2(style12.getName1());
				info.setName1(style12.getName2());
				info.setTime2(style12.getTime1());
				info.setTime1(style12.getTime2());
				info.setMaterialStrength1(style12.getMaterialStrenght2());
				info.setMaterialStrength2(style12.getMaterialStrenght1());

				String move = style12.getMove();

				if (move.equals("o-o")) {
					if (style12.getColor().equals("W")) {
						move = "  e8-g8";
					} else {
						move = "  e1-g1";
					}
				} else if (move.equals("o-o-o")) {
					if (style12.getColor().equals("W")) {
						move = "  e8-c8";
					} else {
						move = "  e1-c1";
					}
				}

				if (!move.substring(0, 1).equals("o") && !move.equals("none")) {
					chessBoard.setPressed(Convertor.letterToNumber(move
							.substring(2, 3)), Integer.valueOf(move.substring(
							3, 4)) - 1);

					memorya = Convertor.letterToNumber(move.substring(2, 3));
					memoryb = Integer.valueOf(move.substring(3, 4)) - 1;
				}
				if (!move.substring(0, 1).equals("o") && !move.equals("none")) {
					chessBoard.setPressed(Convertor.letterToNumber(move
							.substring(5, 6)), Integer.valueOf(move.substring(
							6, 7)) - 1);

					memory2a = Convertor.letterToNumber(move.substring(5, 6));
					memory2b = Integer.valueOf(move.substring(6, 7)) - 1;
				}
				if (style12.getColor().equals("B")) {
					name = style12.getName2();
					time = style12.getTime2();
					move = style12.getMove();

					if (!move.equals("none") && !move.equals("o-o")
							&& !move.equals("o-o-o")) {
						from = move.substring(2, 4);
						logger.debug(from);
						to = move.substring(5, 7);
						logger.debug(to);
						MySQLConnection.insertMove(from, to, time, name);
					} else {
						from = move;
						to = move;
						MySQLConnection.insertMove(from, to, time, name);
					}
				} else {
					name = style12.getName1();
					time = style12.getTime1();
					move = style12.getMove();
					if (!move.equals("none") && !move.equals("o-o")
							&& !move.equals("o-o-o")) {
						from = move.substring(2, 4);
						logger.debug(from);
						to = move.substring(5, 7);
						logger.debug(to);
						MySQLConnection.insertMove(from, to, time, name);
					} else {
						from = move;
						to = move;
						MySQLConnection.insertMove(from, to, time, name);
					}
				}
				MySQLConnection.moveNumber++;
			}
			if (word.equals("Creating:")) {
				time2.startClock();
				letter = 0;
				while (letter != 13) {
					try {
						letter = br.read();
					} catch (Exception e) {
						logger.error("", e);
					}
					word = word.concat(String.valueOf((char) letter));
				}
				logger.debug("CREATING: " + word);
				StringTokenizer creating = new StringTokenizer(word);

				creating.nextToken();
				creating.nextToken();
				String rating1 = creating.nextToken();
				if (rating1.equals("(")) {
					rating1 += creating.nextToken();
				}
				creating.nextToken();
				String rating2 = creating.nextToken();

				if (rating2.equals("(")) {
					rating2 += creating.nextToken();
				}
				logger.debug("RATING1: " + rating1);
				logger.debug("RATING2: " + rating2);
				info.setRating1(rating2);
				info.setRating2(rating1);

				logger.debug("START CLOCK!!!!!!!");
			}
			if (word.equals("{Game")) {
				time2.stopClock();
				logger.debug("STOP CLOCK!!!!!!!");
			}
		}
	}
}
